package com.example.leetcode.util;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AESUtil {
    private static SecretKey loadKeyAES(String secretKey) throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(secretKey.getBytes());
        KeyGenerator gen = KeyGenerator.getInstance("AES");
        gen.init(128, random);
        return gen.generateKey();
    }

    private static byte[] encryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, key);
        return cipher.doFinal(source);
    }

    private static byte[] decryptAES(byte[] source, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, key);
        return cipher.doFinal(source);
    }

    public static String encrypt(String aesKey, String content) {
        try {
            SecretKey secretKey = loadKeyAES(aesKey);
            byte[] encryptContentRequest = encryptAES(content.getBytes(StandardCharsets.UTF_8), secretKey);
            return Base64.getEncoder().encodeToString(encryptContentRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String aesKey, String content) {
        try {
            SecretKey secretKey = loadKeyAES(aesKey);
            byte[] response = decryptAES(Base64.getDecoder().decode(content), secretKey);
            return new String(response);
        } catch (Exception e) {
            return null;
        }
    }
}
